using UnityEngine;
using System.Collections;

public class PlayerWalk : MonoBehaviour
{
	public delegate void OnArriveDestination ();
	
	public OnArriveDestination onArriveDestination;
	
	//radius of walk around area;
	float _radius = 5.0f;
	Vector3 _originPosition;
	Transform _trans;
	float _speed;
	
	public Vector3 direction;
	
	public float speed {
		get{ return _speed;}
		set {
			_speed = value;
		}
	}
	
	/// <summary>
	/// Start this instance.
	/// </summary>
	void Start ()
	{
		_originPosition = transform.localPosition;
		_trans = transform;
	}
	
	public void RepeatWalk (float repeatRate, float radius)
	{
		float t = Time.time;
		_radius = radius;
		InvokeRepeating ("WalkAround", t, repeatRate);
	}
	
	/// <summary>
	/// Walks the around.
	/// </summary>
	void WalkAround ()
	{
		float offset = Random.Range (-1f, 1f) * _radius;
		Vector3 dest = _originPosition + new Vector3 (offset, 0, 0);
		MoveTowards (dest);
	}
	
	/// <summary>
	/// Moves the towards.
	/// </summary>
	/// <param name='destination'>
	/// Destination.
	/// </param>
	public void MoveTowards (Vector3 destination , bool isBorder = false)
	{
		destination.z = _trans.position.z;
		
		Vector3 tempDestination = destination;
		
		if(!isBorder) {
			tempDestination.x = _trans.position.x;
		}
		
		_trans.position = Vector3.MoveTowards (_trans.position, tempDestination, _speed * Time.deltaTime);
		
		if (Vector3.Distance (_trans.position, destination) - 0.03f < 0) {
			onArriveDestination ();
			_trans.position = destination;
			return;
		}
		
		if (direction.x > 0) {
			_trans.localEulerAngles = Vector3.zero;	
		} else {
			_trans.localEulerAngles = new Vector3 (0, 180, 0);
		}
		
	}
}
